package org.hdlh.protocol;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.hdlh.core.RpcProtocol;
import org.hdlh.core.RpcRequest;
import org.hdlh.handler.RpcClientInitializer;

@Slf4j
public class NettyClient {

    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

    private String serviceAddress;
    private int servicePort;

    public NettyClient(String serviceAddress, int servicePort) {
        log.info("begin init netty client, serviceAddress:{}, servicePort:{}", serviceAddress, servicePort);
        this.serviceAddress = serviceAddress;
        this.servicePort = servicePort;
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new RpcClientInitializer());



    }

    public void sendRequest(RpcProtocol<RpcRequest> rpcRequestRpcProtocol) throws InterruptedException {
        final ChannelFuture future = bootstrap.connect(this.serviceAddress, this.servicePort).sync();
        future.addListener(listener->{
            if(future.isSuccess()){
                log.info("connect rpc server {} is success", this.serviceAddress);
            }else{
                log.info("connect rpc server {} is fail", this.serviceAddress);
                future.cause().printStackTrace();
                eventLoopGroup.shutdownGracefully();
            }
        });
        future.channel().writeAndFlush(rpcRequestRpcProtocol);
    }
}


